﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MixScript.Appl.Message;
using MixScriptWeb.control;
using MixScript.BLL.ApplAdmin;
using MixScriptWeb.Share;
using MixScript.Appl.Security.Crypto;
namespace MixScriptWeb.Member
{
    public partial class fAddGroup : cCommonWeb// System.Web.UI.Page
    {



        public enum PageAction
        {
            PageActionAdd,
            PageActionEdit
        }

        private static System.Data.DataTable dtPrivileges;
        PageAction constPageAction = PageAction.PageActionAdd;
        int intCurrentID = 0;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            clsMessageProvider.clsMessageProvider classMessage = new clsMessageProvider.clsMessageProvider();

            if (System.Convert.ToBoolean(~System.Convert.ToInt32(Session["is_login"])))
            {
                Response.Redirect("~/login.aspx");
            }
            else
            {
                if (System.Convert.ToBoolean(~System.Convert.ToInt32(Session["is_hardcoded"])))
                {
                    clsDatabaseUtility.clsDatabaseUtility classDatabase = new clsDatabaseUtility.clsDatabaseUtility();

                    if (System.Convert.ToBoolean(PageAction.PageActionAdd))
                    {
                        if (!classDatabase.CheckMenuPrivileges(3, clsDatabaseUtility.clsDatabaseUtility.PrivilegesAction.actionCanAdd))
                        {
                            //btnSave.Enabled = false;
                        }
                    }
                    else if (System.Convert.ToBoolean(System.Convert.ToBoolean((PageAction.PageActionEdit))))
                    {
                        if (!classDatabase.CheckMenuPrivileges(3, clsDatabaseUtility.clsDatabaseUtility.PrivilegesAction.actionCanEdit))
                        {
                            //btnSave.Enabled = false;
                        }
                    }

                    classDatabase = null;
                }
            }

            if (!Page.IsPostBack)
            {
                InitDataTable();
            }

            if (Request.QueryString.Count > 0)
            {
                if (Request.QueryString["x"].ToString().Trim() != "")
                {
                    constPageAction = PageAction.PageActionEdit;
                    //if (Information.IsNumeric(Request.QueryString["x"].ToString().Trim()))
                    //{
                        intCurrentID = int.Parse(Request.QueryString["x"].ToString().Trim());

                        if (!Page.IsPostBack)
                        {
                            if (!LoadData(intCurrentID))
                            {
                                //MessageContainer.Text = classMessage.showMessage("Error: Unable to load current data...!!!", clsMessageProvider.clsMessageProvider.MessageIcon.IconExclamation, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                            }
                        }
                    }
                    else
                    {
                        intCurrentID = 0;
                    }
                }
                else
                {
                    constPageAction = PageAction.PageActionAdd;
                    intCurrentID = 0;
                }
           // }
            //else
            {
                constPageAction = PageAction.PageActionAdd;
                intCurrentID = 0;
            }

            //GridView1.Columns(8).Visible = False
        }

        private void InitDataTable()
        {
            dtPrivileges = new System.Data.DataTable();

            dtPrivileges.Columns.Add("id_menu");
            dtPrivileges.Columns.Add("action_view");
            dtPrivileges.Columns.Add("action_add");
            dtPrivileges.Columns.Add("action_edit");
            dtPrivileges.Columns.Add("action_delete");
        }

        private bool LoadData(int intID)
        {
            string strSQL = string.Empty;
            DataSet objDataSet;
            clsDatabaseUtility.clsDatabaseUtility classDatabaseUtility = new clsDatabaseUtility.clsDatabaseUtility();
            bool boolRetval = false;

            try
            {
                strSQL = (string)("SELECT * FROM tb_group WHERE id_group = " + intID.ToString());
                objDataSet = classDatabaseUtility.getDataSet(strSQL, true, true);

                if (objDataSet.Tables[0].Rows.Count > 0)
                {
                    txtgroupname.Text = objDataSet.Tables[0].Rows[0]["group_name"].ToString();
                    txtgroupdesc.Text = objDataSet.Tables[0].Rows[0]["group_description"].ToString();

                    if (int.Parse(objDataSet.Tables[0].Rows[0]["published"].ToString()) == 1)
                    {
                        chkPublish.Checked = true;
                    }
                    else
                    {
                        chkPublish.Checked = false;
                    }

                    boolRetval = true;
                }
                else
                {
                    boolRetval = false;
                }

                objDataSet.Dispose();
                objDataSet = null;

                classDatabaseUtility = null;

                return boolRetval;
            }
            catch (Exception)
            {
                return false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            clsMessageProvider.clsMessageProvider classMessageProvider = new clsMessageProvider.clsMessageProvider();

            try
            {
                if (txtgroupname.Text.Trim() == "")
                {
                    MessageContainer.Text = classMessageProvider.showMessage("Please fill in the blanks.", clsMessageProvider.clsMessageProvider.MessageIcon.IconExclamation, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                    txtgroupname.Focus();
                }
                else
                {
                    if (constPageAction == PageAction.PageActionEdit & intCurrentID > 0)
                    {
                        if (UpdateData())
                        {
                            Response.Redirect("~/fGroupMst.aspx");
                        }
                        else
                        {
                            MessageContainer.Text = classMessageProvider.showMessage("Error: Unable to save the changes.", clsMessageProvider.clsMessageProvider.MessageIcon.IconError, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                            txtgroupname.Focus();
                        }
                    }
                    else if (constPageAction == PageAction.PageActionAdd)
                    {
                        if (SaveData())
                        {
                            Response.Redirect("~/fGroupMst.aspx");
                        }
                        else
                        {
                            MessageContainer.Text = classMessageProvider.showMessage("Error: Unable to save the changes.", clsMessageProvider.clsMessageProvider.MessageIcon.IconError, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                            txtgroupname.Focus();
                        }
                    }
                    else
                    {
                        MessageContainer.Text = classMessageProvider.showMessage("Error: Unknown action or invalid handler.", clsMessageProvider.clsMessageProvider.MessageIcon.IconError, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                        txtgroupname.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageContainer.Text = classMessageProvider.showMessage((string)("Error: Unhandled exception has accured.<br />" + ex.Message.ToString() + "<br />" + ex.Source.ToString()), clsMessageProvider.clsMessageProvider.MessageIcon.IconError, clsMessageProvider.clsMessageProvider.MessageAlignment.AlignmentLeft);
                txtgroupname.Focus();
            }
            finally
            {
                classMessageProvider.Dispose();
                classMessageProvider = null;
            }
        }

        private bool UpdateData()
        {
            string strSQL = string.Empty;
            clsDatabaseUtility.clsDatabaseUtility classDatabaseUtility = new clsDatabaseUtility.clsDatabaseUtility();
            int intGroupPublish = 0;


            int intMenuID = 0;

            CheckBox objActionView;
            CheckBox objActionAdd;
            CheckBox objActionEdit;
            CheckBox objActionDelete;
            CheckBox objActionPublish;

            int intView = 0;
            int intAdd = 0;
            int intEdit = 0;
            int intDelete = 0;
            int intPublish = 0;

            bool boolRetval = false;

            try
            {
                if (chkPublish.Checked)
                {
                    intGroupPublish = 1;
                }
                else
                {
                    intGroupPublish = 0;
                }

                strSQL = (string)("UPDATE tb_group SET group_name = \'" + classDatabaseUtility.PreventSQLi(txtgroupname.Text) + "\', " + "group_description = \'" + classDatabaseUtility.PreventSQLi(txtgroupdesc.Text) + "\', published = " + intGroupPublish.ToString() + ", " + "updated_by = 1, updated_datetime = \'" + DateTime.Now + "\' WHERE id_group = " + intCurrentID.ToString());

                if (classDatabaseUtility.ExecuteSQL(strSQL, true, true))
                {
                    ModuleAuditTrail.LogAuditrail(DateTime.Now, System.Convert.ToInt32(Session["user_id"]), "tb_group", "Update", strSQL);
                    strSQL = (string)("DELETE FROM tb_menu_privileges WHERE id_group = " + intCurrentID.ToString());
                    if (classDatabaseUtility.ExecuteSQL(strSQL, true, true))
                    {
                        ModuleAuditTrail.LogAuditrail(DateTime.Now, System.Convert.ToInt32(Session["user_id"]), "tb_group", "Delete", strSQL);
                        //Fill privileges data table
                        foreach (GridViewRow objGridRow in GridView1.Rows)
                        {
                            objActionView = (CheckBox)(objGridRow.FindControl("chkView"));
                            if (objActionView.Checked)
                            {
                                intView = 1;
                            }
                            else
                            {
                                intView = 0;
                            }

                            objActionAdd = (CheckBox)(objGridRow.FindControl("chkAdd"));
                            if (objActionAdd.Checked)
                            {
                                intAdd = 1;
                            }
                            else
                            {
                                intAdd = 0;
                            }

                            objActionEdit = (CheckBox)(objGridRow.FindControl("chkEdit"));
                            if (objActionEdit.Checked)
                            {
                                intEdit = 1;
                            }
                            else
                            {
                                intEdit = 0;
                            }

                            objActionDelete = (CheckBox)(objGridRow.FindControl("chkDelete"));
                            if (objActionDelete.Checked)
                            {
                                intDelete = 1;
                            }
                            else
                            {
                                intDelete = 0;
                            }

                            objActionPublish = (CheckBox)(objGridRow.FindControl("chkPublish"));
                            if (objActionPublish.Checked)
                            {
                                intPublish = 1;
                            }
                            else
                            {
                                intPublish = 0;
                            }

                            intMenuID = System.Convert.ToInt32(GridView1.DataKeys[objGridRow.RowIndex]["id_menu"]);

                            strSQL = "INSERT INTO tb_menu_privileges (id_menu, id_group, action_view, action_add, action_edit, " + "action_delete, action_publish, created_by, created_datetime, updated_by, updated_datetime) VALUES (" + intMenuID.ToString() + ", " + intCurrentID.ToString() + ", " + intView.ToString() + ", " + intAdd.ToString() + ", " + intEdit.ToString() + ", " + intDelete.ToString() + ", " + intPublish.ToString() + ", " + "1, \'" + DateTime.Now + "\', 1, \'" + DateTime.Now + "\')";

                            if (classDatabaseUtility.ExecuteSQL(strSQL, true, true))
                            {
                                ModuleAuditTrail.LogAuditrail(DateTime.Now, System.Convert.ToInt32(Session["user_id"]), "tb_group", "Update", strSQL);
                                boolRetval = true;
                            }
                            else
                            {
                                boolRetval = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        boolRetval = false;
                    }
                }
                else
                {
                    boolRetval = false;
                }

                classDatabaseUtility = null;

                return boolRetval;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private bool SaveData()
        {
            string strSQL = string.Empty;
            clsDatabaseUtility.clsDatabaseUtility classDatabaseUtility;
            DataSet objDataSet;
            int intLastInsertID = 0;
            int intPublishState = 0;
            bool boolRetval = false;

            CheckBox objActionView;
            CheckBox objActionAdd;
            CheckBox objActionEdit;
            CheckBox objActionDelete;
            CheckBox objActionPublish;

            int intView = 0;
            int intAdd = 0;
            int intEdit = 0;
            int intDelete = 0;
            int intPublish = 0;


            int intMenuID = 0;
            int intCounter = 0;

            try
            {
                if (chkPublish.Checked)
                {
                    intPublishState = 1;
                }
                else
                {
                    intPublishState = 0;
                }

                classDatabaseUtility = new clsDatabaseUtility.clsDatabaseUtility();

                strSQL = "INSERT INTO tb_group (group_name, group_description, published, created_by, created_datetime, updated_by, updated_datetime) VALUES (\'" + classDatabaseUtility.PreventSQLi(txtgroupname.Text) + "\', \'" + classDatabaseUtility.PreventSQLi(txtgroupdesc.Text) + "\', " + intPublishState.ToString() + ", 1, \'" + DateTime.Now + "\', 1, \'" + DateTime.Now + "\') SELECT @@IDENTITY AS last_insert_id";

                objDataSet = classDatabaseUtility.getDataSet(strSQL, true, true);
                ModuleAuditTrail.LogAuditrail(DateTime.Now, System.Convert.ToInt32(Session["user_id"]), "tb_group", "Insert", strSQL);
                if (objDataSet.Tables.Count > 0)
                {
                    if (objDataSet.Tables[0].Rows.Count > 0)
                    {
                        //if (Information.IsNumeric(objDataSet.Tables[0].Rows[0]["last_insert_id"].ToString()))
                        //{
                            if (int.Parse(objDataSet.Tables[0].Rows[0]["last_insert_id"].ToString()) > 0)
                            {
                                intLastInsertID = int.Parse(objDataSet.Tables[0].Rows[0]["last_insert_id"].ToString());

                                strSQL = (string)("DELETE FROM tb_menu_privileges WHERE id_group = " + intLastInsertID.ToString());
                                if (classDatabaseUtility.ExecuteSQL(strSQL, true, true))
                                {
                                    //Fill privileges data table
                                    foreach (GridViewRow objGridRow in GridView1.Rows)
                                    {
                                        objActionView = (CheckBox)(objGridRow.FindControl("chkView"));
                                        if (objActionView.Checked)
                                        {
                                            intView = 1;
                                        }
                                        else
                                        {
                                            intView = 0;
                                        }

                                        objActionAdd = (CheckBox)(objGridRow.FindControl("chkAdd"));
                                        if (objActionAdd.Checked)
                                        {
                                            intAdd = 1;
                                        }
                                        else
                                        {
                                            intAdd = 0;
                                        }

                                        objActionEdit = (CheckBox)(objGridRow.FindControl("chkEdit"));
                                        if (objActionEdit.Checked)
                                        {
                                            intEdit = 1;
                                        }
                                        else
                                        {
                                            intEdit = 0;
                                        }

                                        objActionDelete = (CheckBox)(objGridRow.FindControl("chkDelete"));
                                        if (objActionDelete.Checked)
                                        {
                                            intDelete = 1;
                                        }
                                        else
                                        {
                                            intDelete = 0;
                                        }

                                        objActionPublish = (CheckBox)(objGridRow.FindControl("chkPublish"));
                                        if (objActionPublish.Checked)
                                        {
                                            intPublish = 1;
                                        }
                                        else
                                        {
                                            intPublish = 0;
                                        }

                                        intMenuID = System.Convert.ToInt32(GridView1.DataKeys[objGridRow.RowIndex]["id_menu"]);

                                        strSQL = "INSERT INTO tb_menu_privileges (id_menu, id_group, action_view, action_add, action_edit, " + "action_delete, action_publish, created_by, created_datetime, updated_by, updated_datetime) VALUES (" + intMenuID.ToString() + ", " + intLastInsertID.ToString() + ", " + intView.ToString() + ", " + intAdd.ToString() + ", " + intEdit.ToString() + ", " + intDelete.ToString() + ", " + intPublish.ToString() + ", " + "1, \'" + DateTime.Now + "\', 1, \'" + DateTime.Now + "\')";

                                        if (classDatabaseUtility.ExecuteSQL(strSQL, true, true))
                                        {
                                            ModuleAuditTrail.LogAuditrail(DateTime.Now, System.Convert.ToInt32(Session["user_id"]), "tb_menu_privileges", "Insert", strSQL);
                                            boolRetval = true;
                                        }
                                        else
                                        {
                                            boolRetval = false;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    boolRetval = false;
                                }
                            //}
                            //else
                            //{
                            //    boolRetval = false;
                            //}
                        }
                        else
                        {
                            boolRetval = false;
                        }
                    }
                    else
                    {
                        boolRetval = false;
                    }

                    objDataSet.Dispose();
                    objDataSet = null;

                    return boolRetval;
                }
                else
                {
                    boolRetval = false;
                }

                classDatabaseUtility = null;

                return boolRetval;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return false;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/fGroup.aspx");
        }

        private void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            int intState = 0;

            string strSQL = string.Empty;
            string strSQL2 = string.Empty;
            DataSet objDataSet;
            DataSet objDataSet2;
            clsDatabaseUtility.clsDatabaseUtility classDatabaseUtility;

            CheckBox chkView;
            CheckBox chkAdd;
            CheckBox chkEdit;
            CheckBox chkDelete;
            CheckBox chkPublish;

            if (e.Row != null)
            {
                if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
                {
                    chkView = (CheckBox)(e.Row.FindControl("chkView"));
                    chkAdd = (CheckBox)(e.Row.FindControl("chkAdd"));
                    chkEdit = (CheckBox)(e.Row.FindControl("chkEdit"));
                    chkDelete = (CheckBox)(e.Row.FindControl("chkDelete"));
                    chkPublish = (CheckBox)(e.Row.FindControl("chkPublish"));

                    classDatabaseUtility = new clsDatabaseUtility.clsDatabaseUtility();

                    if (constPageAction == PageAction.PageActionEdit)
                    {
                        strSQL2 = "SELECT * FROM tb_menu_privileges WHERE id_group = " + intCurrentID.ToString() + " AND id_menu = " + GridView1.DataKeys[e.Row.RowIndex]["id_menu"].ToString();
                        objDataSet2 = classDatabaseUtility.getDataSet(strSQL2, true, true);

                        if (objDataSet2.Tables.Count > 0)
                        {
                            if (objDataSet2.Tables[0].Rows.Count > 0)
                            {
                                if (int.Parse(objDataSet2.Tables[0].Rows[0]["action_view"].ToString()) > 0)
                                {
                                    chkView.Checked = true;
                                }
                                else
                                {
                                    chkView.Checked = false;
                                }

                                if (int.Parse(objDataSet2.Tables[0].Rows[0]["action_add"].ToString()) > 0)
                                {
                                    chkAdd.Checked = true;
                                }
                                else
                                {
                                    chkAdd.Checked = false;
                                }

                                if (int.Parse(objDataSet2.Tables[0].Rows[0]["action_edit"].ToString()) > 0)
                                {
                                    chkEdit.Checked = true;
                                }
                                else
                                {
                                    chkEdit.Checked = false;
                                }

                                if (int.Parse(objDataSet2.Tables[0].Rows[0]["action_delete"].ToString()) > 0)
                                {
                                    chkDelete.Checked = true;
                                }
                                else
                                {
                                    chkDelete.Checked = false;
                                }

                                if (int.Parse(objDataSet2.Tables[0].Rows[0]["action_publish"].ToString()) > 0)
                                {
                                    chkPublish.Checked = true;
                                }
                                else
                                {
                                    chkPublish.Checked = false;
                                }
                            }
                            else
                            {
                                chkView.Checked = false;
                                chkAdd.Checked = false;
                                chkEdit.Checked = false;
                                chkDelete.Checked = false;
                                chkPublish.Checked = false;
                            }
                        }
                        else
                        {
                            chkView.Checked = false;
                            chkAdd.Checked = false;
                            chkEdit.Checked = false;
                            chkDelete.Checked = false;
                            chkPublish.Checked = false;
                        }

                        objDataSet2.Dispose();
                        objDataSet2 = null;
                    }

                    strSQL = "SELECT * FROM menu_config WHERE id_menu = " + GridView1.DataKeys[e.Row.RowIndex]["id_menu"].ToString();
                    objDataSet = classDatabaseUtility.getDataSet(strSQL, true, true);

                    if (objDataSet.Tables.Count > 0)
                    {
                        if (objDataSet.Tables[0].Rows.Count > 0)
                        {
                            if (int.Parse(objDataSet.Tables[0].Rows[0]["has_view"].ToString()) == 1)
                            {
                                chkView.Visible = true;
                            }
                            else
                            {
                                chkView.Visible = false;
                            }

                            if (int.Parse(objDataSet.Tables[0].Rows[0]["has_add"].ToString()) == 1)
                            {
                                chkAdd.Visible = true;
                            }
                            else
                            {
                                chkAdd.Visible = false;
                            }

                            if (int.Parse(objDataSet.Tables[0].Rows[0]["has_edit"].ToString()) == 1)
                            {
                                chkEdit.Visible = true;
                            }
                            else
                            {
                                chkEdit.Visible = false;
                            }

                            if (int.Parse(objDataSet.Tables[0].Rows[0]["has_delete"].ToString()) == 1)
                            {
                                chkDelete.Visible = true;
                            }
                            else
                            {
                                chkDelete.Visible = false;
                            }

                            if (int.Parse(objDataSet.Tables[0].Rows[0]["has_publish"].ToString()) == 1)
                            {
                                chkPublish.Visible = true;
                            }
                            else
                            {
                                chkPublish.Visible = false;
                            }
                        }
                        else
                        {
                            chkView.Visible = false;
                            chkAdd.Visible = false;
                            chkEdit.Visible = false;
                            chkDelete.Visible = false;
                            chkPublish.Visible = false;
                        }
                    }
                    else
                    {
                        chkView.Visible = false;
                        chkAdd.Visible = false;
                        chkEdit.Visible = false;
                        chkDelete.Visible = false;
                        chkPublish.Visible = false;
                    }
                }
            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}